package cc.tuhaolicai.mt.user.mobile.business.util;


import cc.tuhaolicai.mt.user.mobile.business.model.Node;
import cc.tuhaolicai.mt.user.mobile.business.model.Workflow;
import cc.tuhaolicai.mt.user.mobile.tool.ToolDate;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.Objects;

/**
 * Workflow工具类
 *
 * @author chenli
 * @create 2017-10-12
 */
public class WorkflowUtil {

    /**
     * 创建业务链
     *
     * @param name：业务链名称
     * @param orderNo：订单号
     */
    public static Workflow buildWorkflow(String name, String orderNo) {
        Workflow workflow = new Workflow();
        workflow.setName(name);
        workflow.setOrderNo(orderNo);
        workflow.setStatus(0);
        workflow.setAddTime(ToolDate.getDate());
        return workflow;
    }

    /**
     * 创建业务链节点
     *
     * @param nodeName：节点名称     //     * @param orderNo：所属业务链订单号
     * @param sort：排序
     * @param startParams：开始时参数
     */
    public static Node buildWorkflowNode(String nodeName, Integer sort, String startParams, String handlerClassName) {
        Node node = new Node();
        node.setNodeName(nodeName);
        node.setStartParams(startParams);
        node.setAddTime(ToolDate.getDate());
        node.setSort(sort);
        node.setStatus(0);
        node.setHandlerClassName(handlerClassName);
        return node;
    }

    /**
     * 将节点添入业务链中
     * 若业务链中含有则删除原数据
     *
     * @param workflow：业务链
     * @param node：节点
     */
    public static Workflow addWorkflowNode(Workflow workflow, Node node) {
        node.setOrderNo(workflow.getOrderNo());
        List<Node> nodeLinkedList = workflow.getNodeLinkedList();
        if (nodeLinkedList == null) {
            nodeLinkedList = Lists.newLinkedList();
        }
        if (!nodeLinkedList.isEmpty()) {
            nodeLinkedList.removeIf(oldNode -> Objects.equals(oldNode.getSort(), node.getSort()));
        }
        nodeLinkedList.add(node);
        workflow.setNodeLinkedList(nodeLinkedList);
        return workflow;
    }

    /**
     * 删除原业务节点
     * 添加新业务节点
     *
     * @param workflow：
     * @param node：
     */
    public static Workflow updateWorkflowNode(Workflow workflow, Node node) {
        List<Node> nodeLinkedList = workflow.getNodeLinkedList();
        nodeLinkedList.removeIf(oldNode -> Objects.equals(oldNode.getSort(), node.getSort()));
        nodeLinkedList.add(node);
        return workflow;
    }

    public static Node findWorkflowNode(Workflow workflow, Integer sort) {
        List<Node> nodeLinkedList = workflow.getNodeLinkedList();
        if (nodeLinkedList == null || nodeLinkedList.size() == 0) {
            return null;
        }
        for (Node oldNode :
                nodeLinkedList) {
            if (Objects.equals(oldNode.getSort(), sort)) {
                return oldNode;
            }
        }
        return null;
    }
}